import { 
  RowData, 
  CellValue, 
  CellChange, 
  Column 
} from '../types'

// 操作类型
enum OperationType {
  SetCell = 'set-cell',
  InsertRow = 'insert-row',
  DeleteRow = 'delete-row',
  UpdateRow = 'update-row',
  BatchUpdate = 'batch-update'
}

// 操作记录
interface Operation {
  type: OperationType
  timestamp: number
  data: any
}

// 单元格操作
interface SetCellOperation extends Operation {
  type: OperationType.SetCell
  data: {
    row: number
    field: string
    oldValue: CellValue
    newValue: CellValue
  }
}

// 插入行操作
interface InsertRowOperation extends Operation {
  type: OperationType.InsertRow
  data: {
    index: number
    row: RowData
  }
}

// 删除行操作
interface DeleteRowOperation extends Operation {
  type: OperationType.DeleteRow
  data: {
    index: number
    row: RowData
  }
}

// 更新行操作
interface UpdateRowOperation extends Operation {
  type: OperationType.UpdateRow
  data: {
    index: number
    oldRow: RowData
    newRow: RowData
  }
}

// 批量更新操作
interface BatchUpdateOperation extends Operation {
  type: OperationType.BatchUpdate
  data: {
    updates: Array<{
      row: number
      field: string
      oldValue: CellValue
      newValue: CellValue
    }>
  }
}

type HistoryOperation = SetCellOperation | InsertRowOperation | DeleteRowOperation | UpdateRowOperation | BatchUpdateOperation

export class DataManager {
  private data: RowData[] = []
  private originalData: RowData[] = []  // 保存原始数据
  private columns: Column[] = []
  private history: HistoryOperation[] = []
  private historyIndex: number = -1
  private maxHistorySize: number = 100
  private modifiedCells: Set<string> = new Set()
  private insertedRows: Set<number> = new Set()
  private deletedRows: Map<number, RowData> = new Map()
  
  // 批量操作相关
  private batchMode: boolean = false
  private batchOperations: Array<{
    row: number
    field: string
    oldValue: CellValue
    newValue: CellValue
  }> = []

  constructor(columns: Column[]) {
    this.columns = columns
  }

  // 设置数据
  setData(data: RowData[]): void {
    // 使用浅拷贝优化性能（假设行数据是扁平对象）
    this.data = this.cloneRows(data)
    this.originalData = this.cloneRows(data)
    this.clearHistory()
    this.clearModifications()
  }

  // 获取数据
  getData(): RowData[] {
    // 使用浅拷贝优化性能
    return this.cloneRows(this.data)
  }

  // 获取原始数据
  getOriginalData(): RowData[] {
    // 使用浅拷贝优化性能
    return this.cloneRows(this.originalData)
  }

  // 获取行数
  getRowCount(): number {
    if (this.filteredIndices !== null) {
      return this.filteredIndices.length
    }
    return this.data.length
  }

  // 获取列数
  getColumnCount(): number {
    return this.columns.length
  }

  // 设置列配置
  setColumns(columns: Column[]): void {
    this.columns = columns
  }

  // 获取单元格值
  getCellValue(row: number, field: string): CellValue {
    const actualRow = this.getActualRowIndex(row)
    if (actualRow < 0 || actualRow >= this.data.length) {
      return null
    }
    return this.data[actualRow][field]
  }

  // 获取单元格原始值
  getOriginalCellValue(row: number, field: string): CellValue {
    // 如果是新插入的行，原始值为null
    if (this.insertedRows.has(row)) {
      return null
    }
    
    // 如果行索引超出原始数据范围，返回null
    if (row < 0 || row >= this.originalData.length) {
      return null
    }
    
    return this.originalData[row][field]
  }

  // 设置单元格值
  setCellValue(row: number, field: string, value: CellValue): boolean {
    const actualRow = this.getActualRowIndex(row)
    if (actualRow < 0 || actualRow >= this.data.length) {
      return false
    }

    const oldValue = this.data[actualRow][field]
    if (oldValue === value) {
      return false
    }

    // 如果在批量模式，收集操作
    if (this.batchMode) {
      this.batchOperations.push({ row: actualRow, field, oldValue, newValue: value })
      this.data[actualRow][field] = value
      this.markCellModified(actualRow, field)
      return true
    }

    // 记录操作
    const operation: SetCellOperation = {
      type: OperationType.SetCell,
      timestamp: Date.now(),
      data: { row: actualRow, field, oldValue, newValue: value }
    }
    this.addToHistory(operation)

    // 执行操作
    this.data[actualRow][field] = value
    
    // 标记修改
    this.markCellModified(actualRow, field)
    
    // 检查是否需要重新过滤
    if (this.filterConfig.has(field)) {
      this.applyFilters()
    }
    
    return true
  }

  // 批量设置单元格值
  batchSetCellValues(updates: Array<{ row: number; field: string; value: CellValue }>): boolean {
    if (updates.length === 0) return false
    
    this.beginBatch()
    
    try {
      updates.forEach(update => {
        this.setCellValue(update.row, update.field, update.value)
      })
      
      this.endBatch()
      return true
    } catch (error) {
      this.cancelBatch()
      throw error
    }
  }

  // 开始批量操作
  beginBatch(): void {
    this.batchMode = true
    this.batchOperations = []
  }

  // 结束批量操作
  endBatch(): void {
    if (!this.batchMode) return
    
    this.batchMode = false
    
    if (this.batchOperations.length > 0) {
      // 创建批量操作记录
      const operation: BatchUpdateOperation = {
        type: OperationType.BatchUpdate,
        timestamp: Date.now(),
        data: { updates: [...this.batchOperations] }
      }
      this.addToHistory(operation)
    }
    
    this.batchOperations = []
  }

  // 取消批量操作
  cancelBatch(): void {
    if (!this.batchMode) return
    
    // 回滚批量操作
    this.batchOperations.reverse().forEach(op => {
      this.data[op.row][op.field] = op.oldValue
      this.unmarkCellModified(op.row, op.field)
    })
    
    this.batchMode = false
    this.batchOperations = []
  }

  // 插入行
  insertRow(index: number, row?: RowData): void {
    const newRow = row || this.createEmptyRow()
    
    const operation: InsertRowOperation = {
      type: OperationType.InsertRow,
      timestamp: Date.now(),
      data: { index, row: newRow }
    }
    this.addToHistory(operation)

    this.data.splice(index, 0, newRow)
    this.insertedRows.add(index)
    
    // 更新插入行索引
    this.updateInsertedRowIndices(index, 1)
  }

  // 删除行
  deleteRow(index: number): boolean {
    if (index < 0 || index >= this.data.length) {
      return false
    }

    const deletedRow = this.data[index]
    
    const operation: DeleteRowOperation = {
      type: OperationType.DeleteRow,
      timestamp: Date.now(),
      data: { index, row: deletedRow }
    }
    this.addToHistory(operation)

    this.data.splice(index, 1)
    
    // 如果是新插入的行，直接从插入列表中删除
    if (this.insertedRows.has(index)) {
      this.insertedRows.delete(index)
    } else {
      // 否则记录为删除的行
      this.deletedRows.set(index, deletedRow)
    }
    
    // 更新插入行索引
    this.updateInsertedRowIndices(index, -1)
    
    return true
  }

  // 更新行
  updateRow(index: number, newRow: RowData): boolean {
    if (index < 0 || index >= this.data.length) {
      return false
    }

    const oldRow = this.cloneRow(this.data[index])
    
    const operation: UpdateRowOperation = {
      type: OperationType.UpdateRow,
      timestamp: Date.now(),
      data: { index, oldRow, newRow: this.cloneRow(newRow) }
    }
    this.addToHistory(operation)

    this.data[index] = this.cloneRow(newRow)
    
    // 标记所有字段为已修改
    this.columns.forEach(col => {
      if (oldRow[col.field] !== newRow[col.field]) {
        this.markCellModified(index, col.field)
      }
    })
    
    return true
  }

  // 撤销
  undo(): boolean {
    if (!this.canUndo()) {
      return false
    }

    const operation = this.history[this.historyIndex]
    this.applyOperation(operation, true)
    this.historyIndex--
    
    return true
  }

  // 重做
  redo(): boolean {
    if (!this.canRedo()) {
      return false
    }

    this.historyIndex++
    const operation = this.history[this.historyIndex]
    this.applyOperation(operation, false)
    
    return true
  }

  // 是否可以撤销
  canUndo(): boolean {
    return this.historyIndex >= 0
  }

  // 是否可以重做
  canRedo(): boolean {
    return this.historyIndex < this.history.length - 1
  }

  // 获取修改的单元格
  getModifiedCells(): Set<string> {
    return new Set(this.modifiedCells)
  }

  // 获取插入的行
  getInsertedRows(): Set<number> {
    return new Set(this.insertedRows)
  }

  // 获取删除的行
  getDeletedRows(): Map<number, RowData> {
    return new Map(this.deletedRows)
  }

  // 是否有修改
  hasChanges(): boolean {
    return this.modifiedCells.size > 0 || 
           this.insertedRows.size > 0 || 
           this.deletedRows.size > 0
  }

  // 获取变更列表（改进版）
  getChanges(): CellChange[] {
    const changes: CellChange[] = []
    
    this.modifiedCells.forEach(key => {
      const [row, field] = key.split(':')
      const rowIndex = parseInt(row)
      
      if (rowIndex < this.data.length) {
        changes.push({
          row: rowIndex,
          col: this.columns.findIndex(c => c.field === field),
          field,
          oldValue: this.getOriginalCellValue(rowIndex, field),
          newValue: this.data[rowIndex][field]
        })
      }
    })
    
    return changes
  }

  // 获取修改的行数据
  getModifiedRows(): Array<{ index: number; original: RowData; current: RowData }> {
    const modifiedRows: Array<{ index: number; original: RowData; current: RowData }> = []
    const rowIndices = new Set<number>()
    
    // 收集有修改的行索引
    this.modifiedCells.forEach(key => {
      const [row] = key.split(':')
      rowIndices.add(parseInt(row))
    })
    
    // 获取修改的行数据
    rowIndices.forEach(index => {
      if (index < this.data.length && !this.insertedRows.has(index)) {
        modifiedRows.push({
          index,
          original: this.originalData[index] || {},
          current: this.data[index]
        })
      }
    })
    
    return modifiedRows
  }

  // 获取插入的行数据
  getInsertedRowsData(): Array<{ index: number; data: RowData }> {
    const insertedRowsData: Array<{ index: number; data: RowData }> = []
    
    this.insertedRows.forEach(index => {
      if (index < this.data.length) {
        insertedRowsData.push({
          index,
          data: this.data[index]
        })
      }
    })
    
    return insertedRowsData.sort((a, b) => a.index - b.index)
  }

  // 提交修改
  commit(): void {
    // 更新原始数据（使用浅拷贝）
    this.originalData = this.cloneRows(this.data)
    this.clearModifications()
    this.clearHistory()
  }

  // 回滚修改
  rollback(): void {
    // 恢复到原始数据（使用浅拷贝）
    this.data = this.cloneRows(this.originalData)
    this.clearModifications()
    this.clearHistory()
  }

  // 性能优化：获取可见区域的数据
  getVisibleData(startRow: number, endRow: number): RowData[] {
    if (this.filteredIndices !== null) {
      const result: RowData[] = []
      for (let i = startRow; i <= endRow && i < this.filteredIndices.length; i++) {
        result.push(this.data[this.filteredIndices[i]])
      }
      return result
    }
    return this.data.slice(startRow, Math.min(endRow + 1, this.data.length))
  }

  // 私有方法

  private deepClone<T>(obj: T): T {
    if (obj === null || typeof obj !== 'object') {
      return obj
    }
    if (obj instanceof Date) {
      return new Date(obj.getTime()) as any
    }
    if (Array.isArray(obj)) {
      return obj.map(item => this.deepClone(item)) as any
    }
    const cloned = {} as T
    for (const key in obj) {
      cloned[key] = this.deepClone(obj[key])
    }
    return cloned
  }
  
  // 优化的行数据拷贝（仅拷贝一层）
  private cloneRow(row: RowData): RowData {
    return { ...row }
  }
  
  // 优化的批量行数据拷贝
  private cloneRows(rows: RowData[]): RowData[] {
    return rows.map(row => ({ ...row }))
  }

  private createEmptyRow(): RowData {
    const row: RowData = {}
    this.columns.forEach(col => {
      row[col.field] = null
    })
    return row
  }

  private addToHistory(operation: HistoryOperation): void {
    // 如果不在历史末尾，删除后续历史
    if (this.historyIndex < this.history.length - 1) {
      this.history = this.history.slice(0, this.historyIndex + 1)
    }

    // 添加新操作
    this.history.push(operation)
    this.historyIndex++

    // 限制历史大小
    if (this.history.length > this.maxHistorySize) {
      this.history.shift()
      this.historyIndex--
    }
  }

  private applyOperation(operation: HistoryOperation, reverse: boolean): void {
    switch (operation.type) {
      case OperationType.SetCell:
        this.applySetCell(operation.data, reverse)
        break
      case OperationType.InsertRow:
        this.applyInsertRow(operation.data, reverse)
        break
      case OperationType.DeleteRow:
        this.applyDeleteRow(operation.data, reverse)
        break
      case OperationType.UpdateRow:
        this.applyUpdateRow(operation.data, reverse)
        break
      case OperationType.BatchUpdate:
        this.applyBatchUpdate(operation.data, reverse)
        break
    }
  }

  private applySetCell(data: SetCellOperation['data'], reverse: boolean): void {
    const { row, field, oldValue, newValue } = data
    this.data[row][field] = reverse ? oldValue : newValue
    
    if (reverse && oldValue === null) {
      this.unmarkCellModified(row, field)
    } else {
      this.markCellModified(row, field)
    }
  }

  private applyInsertRow(data: InsertRowOperation['data'], reverse: boolean): void {
    const { index, row } = data
    
    if (reverse) {
      this.data.splice(index, 1)
      this.insertedRows.delete(index)
    } else {
      this.data.splice(index, 0, this.cloneRow(row))
      this.insertedRows.add(index)
    }
    
    this.updateInsertedRowIndices(index, reverse ? -1 : 1)
  }

  private applyDeleteRow(data: DeleteRowOperation['data'], reverse: boolean): void {
    const { index, row } = data
    
    if (reverse) {
      this.data.splice(index, 0, this.cloneRow(row))
      this.deletedRows.delete(index)
    } else {
      this.data.splice(index, 1)
      this.deletedRows.set(index, row)
    }
    
    this.updateInsertedRowIndices(index, reverse ? 1 : -1)
  }

  private applyUpdateRow(data: UpdateRowOperation['data'], reverse: boolean): void {
    const { index, oldRow, newRow } = data
    this.data[index] = this.cloneRow(reverse ? oldRow : newRow)
    
    // 更新修改标记
    this.columns.forEach(col => {
      const field = col.field
      if (oldRow[field] !== newRow[field]) {
        if (reverse) {
          this.unmarkCellModified(index, field)
        } else {
          this.markCellModified(index, field)
        }
      }
    })
  }

  private applyBatchUpdate(data: BatchUpdateOperation['data'], reverse: boolean): void {
    const updates = reverse ? [...data.updates].reverse() : data.updates
    
    updates.forEach(update => {
      this.data[update.row][update.field] = reverse ? update.oldValue : update.newValue
      
      if (reverse && this.getOriginalCellValue(update.row, update.field) === update.oldValue) {
        this.unmarkCellModified(update.row, update.field)
      } else {
        this.markCellModified(update.row, update.field)
      }
    })
  }

  private markCellModified(row: number, field: string): void {
    this.modifiedCells.add(`${row}:${field}`)
  }

  private unmarkCellModified(row: number, field: string): void {
    this.modifiedCells.delete(`${row}:${field}`)
  }

  private updateInsertedRowIndices(fromIndex: number, offset: number): void {
    const newInsertedRows = new Set<number>()
    
    this.insertedRows.forEach(index => {
      if (index > fromIndex) {
        newInsertedRows.add(index + offset)
      } else {
        newInsertedRows.add(index)
      }
    })
    
    this.insertedRows = newInsertedRows
  }

  private clearHistory(): void {
    this.history = []
    this.historyIndex = -1
  }

  private clearModifications(): void {
    this.modifiedCells.clear()
    this.insertedRows.clear()
    this.deletedRows.clear()
  }

  // 检查单元格是否被修改
  isCellModified(row: number, field: string): boolean {
    return this.modifiedCells.has(`${row}:${field}`)
  }

  // 检查行是否被修改
  isRowModified(row: number): boolean {
    for (const key of this.modifiedCells) {
      const [r] = key.split(':')
      if (parseInt(r) === row) {
        return true
      }
    }
    return false
  }

  // 检查行是否是新插入的
  isRowInserted(row: number): boolean {
    return this.insertedRows.has(row)
  }

  // 清理无效的修改标记
  private cleanupModifications(): void {
    // 清理超出数据范围的修改标记
    const validModifiedCells = new Set<string>()
    this.modifiedCells.forEach(key => {
      const [row] = key.split(':')
      if (parseInt(row) < this.data.length) {
        validModifiedCells.add(key)
      }
    })
    this.modifiedCells = validModifiedCells
    
    // 清理超出数据范围的插入标记
    const validInsertedRows = new Set<number>()
    this.insertedRows.forEach(row => {
      if (row < this.data.length) {
        validInsertedRows.add(row)
      }
    })
    this.insertedRows = validInsertedRows
  }
  
  // ===== 过滤功能 =====
  
  // 过滤配置
  private filterConfig: Map<string, {
    value: any
    operator: 'equals' | 'contains' | 'startsWith' | 'endsWith' | 'gt' | 'gte' | 'lt' | 'lte' | 'between' | 'in' | 'notIn' | 'custom'
    filterFn?: (value: any, filterValue: any) => boolean
  }> = new Map()
  
  // 过滤后的数据索引
  private filteredIndices: number[] | null = null
  
  // 设置列过滤
  setColumnFilter(
    columnField: string, 
    value: any, 
    operator: 'equals' | 'contains' | 'startsWith' | 'endsWith' | 'gt' | 'gte' | 'lt' | 'lte' | 'between' | 'in' | 'notIn' | 'custom' = 'contains',
    filterFn?: (value: any, filterValue: any) => boolean
  ): void {
    if (value === null || value === undefined || value === '') {
      // 清除过滤
      this.filterConfig.delete(columnField)
    } else {
      this.filterConfig.set(columnField, { value, operator, filterFn })
    }
    
    // 重新应用过滤
    this.applyFilters()
  }
  
  // 清除列过滤
  clearColumnFilter(columnField: string): void {
    this.filterConfig.delete(columnField)
    this.applyFilters()
  }
  
  // 清除所有过滤
  clearAllFilters(): void {
    this.filterConfig.clear()
    this.filteredIndices = null
  }
  
  // 获取过滤配置
  getFilterConfig() {
    const config: Record<string, any> = {}
    this.filterConfig.forEach((value, key) => {
      config[key] = { ...value }
    })
    return config
  }
  
  // 应用过滤
  private applyFilters(): void {
    if (this.filterConfig.size === 0) {
      this.filteredIndices = null
      return
    }
    
    this.filteredIndices = []
    
    for (let i = 0; i < this.data.length; i++) {
      const row = this.data[i]
      let passFilter = true
      
      // 检查每个过滤条件
      for (const [field, config] of this.filterConfig) {
        const cellValue = row[field]
        const filterValue = config.value
        
        if (!this.checkFilter(cellValue, filterValue, config.operator, config.filterFn)) {
          passFilter = false
          break
        }
      }
      
      if (passFilter) {
        this.filteredIndices.push(i)
      }
    }
  }
  
  // 检查单个过滤条件
  private checkFilter(
    cellValue: any, 
    filterValue: any, 
    operator: string,
    filterFn?: (value: any, filterValue: any) => boolean
  ): boolean {
    // 自定义过滤函数
    if (operator === 'custom' && filterFn) {
      return filterFn(cellValue, filterValue)
    }
    
    // 处理null/undefined
    if (cellValue == null) {
      return operator === 'equals' && filterValue == null
    }
    
    // 转换为字符串进行比较（对于字符串操作）
    const cellStr = String(cellValue).toLowerCase()
    const filterStr = String(filterValue).toLowerCase()
    
    switch (operator) {
      case 'equals':
        return cellValue === filterValue
      case 'contains':
        return cellStr.includes(filterStr)
      case 'startsWith':
        return cellStr.startsWith(filterStr)
      case 'endsWith':
        return cellStr.endsWith(filterStr)
      case 'gt':
        return cellValue > filterValue
      case 'gte':
        return cellValue >= filterValue
      case 'lt':
        return cellValue < filterValue
      case 'lte':
        return cellValue <= filterValue
      case 'between':
        return Array.isArray(filterValue) && 
               filterValue.length === 2 && 
               cellValue >= filterValue[0] && 
               cellValue <= filterValue[1]
      case 'in':
        return Array.isArray(filterValue) && filterValue.includes(cellValue)
      case 'notIn':
        return Array.isArray(filterValue) && !filterValue.includes(cellValue)
      default:
        return true
    }
  }
  
  // 获取实际行索引（考虑过滤）
  private getActualRowIndex(visibleRow: number): number {
    if (this.filteredIndices !== null) {
      if (visibleRow >= 0 && visibleRow < this.filteredIndices.length) {
        return this.filteredIndices[visibleRow]
      }
      return -1
    }
    return visibleRow
  }
  
  // 获取可见行索引（从实际行索引）
  private getVisibleRowIndex(actualRow: number): number {
    if (this.filteredIndices !== null) {
      return this.filteredIndices.indexOf(actualRow)
    }
    return actualRow
  }

  // ===== 排序功能（只负责排序数据，不保存状态） =====
  
  // 排序数据（本地排序）
  sortByColumn(columnField: string, direction: 'asc' | 'desc', customCompareFn?: (a: any, b: any) => number): void {
    // 创建索引数组来跟踪原始位置
    const indexedData = this.data.map((row, index) => ({ row, originalIndex: index }))
    
    // 排序
    indexedData.sort((a, b) => {
      const valueA = a.row[columnField]
      const valueB = b.row[columnField]
      
      // 使用自定义比较函数
      if (customCompareFn) {
        const result = customCompareFn(valueA, valueB)
        return direction === 'asc' ? result : -result
      }
      
      // 处理null/undefined值
      if (valueA == null && valueB == null) return 0
      if (valueA == null) return direction === 'asc' ? -1 : 1
      if (valueB == null) return direction === 'asc' ? 1 : -1
      
      // 数字比较
      if (typeof valueA === 'number' && typeof valueB === 'number') {
        return direction === 'asc' ? valueA - valueB : valueB - valueA
      }
      
      // 日期比较
      if (valueA instanceof Date && valueB instanceof Date) {
        return direction === 'asc' 
          ? valueA.getTime() - valueB.getTime() 
          : valueB.getTime() - valueA.getTime()
      }
      
      // 字符串比较（不区分大小写）
      const strA = String(valueA).toLowerCase()
      const strB = String(valueB).toLowerCase()
      
      if (strA < strB) return direction === 'asc' ? -1 : 1
      if (strA > strB) return direction === 'asc' ? 1 : -1
      return 0
    })
    
    // 更新数据数组
    this.data = indexedData.map(item => item.row)
    
    // 更新修改标记的行索引
    this.updateModificationIndicesAfterSort(indexedData)
  }
  
  // 恢复原始顺序
  restoreOriginalOrder(): void {
    // 恢复到原始数据的顺序
    const originalOrder = new Map<RowData, number>()
    this.originalData.forEach((row, index) => {
      originalOrder.set(row, index)
    })
    
    // 按原始顺序排序当前数据
    this.data.sort((a, b) => {
      const indexA = originalOrder.get(a) ?? Number.MAX_VALUE
      const indexB = originalOrder.get(b) ?? Number.MAX_VALUE
      return indexA - indexB
    })
  }
  
  // 排序后更新修改标记的索引
  private updateModificationIndicesAfterSort(indexedData: Array<{ row: RowData; originalIndex: number }>): void {
    // 创建旧索引到新索引的映射
    const indexMap = new Map<number, number>()
    indexedData.forEach((item, newIndex) => {
      indexMap.set(item.originalIndex, newIndex)
    })
    
    // 更新修改的单元格标记
    const newModifiedCells = new Set<string>()
    this.modifiedCells.forEach(key => {
      const [row, field] = key.split(':')
      const oldRowIndex = parseInt(row)
      const newRowIndex = indexMap.get(oldRowIndex)
      if (newRowIndex !== undefined) {
        newModifiedCells.add(`${newRowIndex}:${field}`)
      }
    })
    this.modifiedCells = newModifiedCells
    
    // 更新插入的行标记
    const newInsertedRows = new Set<number>()
    this.insertedRows.forEach(oldIndex => {
      const newIndex = indexMap.get(oldIndex)
      if (newIndex !== undefined) {
        newInsertedRows.add(newIndex)
      }
    })
    this.insertedRows = newInsertedRows
  }
} 